// fileName      :  dblog.go
// createdAt     :  2022-01-11
// description   :

package dblog

import (
	"log"
	"os"
	"path/filepath"
	"strings"
	"time"
	"zl-gin/config"
	"zl-gin/utils"
)

func GetLogType() *log.Logger {
	conf := config.Get().Gorm

	if conf.Output == "console" {
		return consoleLog()
	} else {
		return fileLog()
	}

}

//consoleLog SQL打印到控制台
func consoleLog() *log.Logger {
	return log.New(os.Stdout, "\r\n", log.LstdFlags)
}

//fileLog SQL语句保存到文件内
func fileLog() *log.Logger {
	conf := config.Get().Gorm

	execDir := utils.GetExecDirectory()
	logPath := execDir + conf.LogDir
	utils.CheckDirExistsAndMk(logPath)

	fileName := strings.Replace(conf.LogFile, `Y%`, utils.Int2String(time.Now().Year()), 1)
	fileName = strings.Replace(fileName, `m%`, utils.Int2String(int(time.Now().Month())), 2)
	fileName = strings.Replace(fileName, `d%`, utils.Int2String(time.Now().Day()), 3)

	logFile := filepath.Join(logPath, fileName)

	log.Println("log file path", logFile)

	file, fileErr := os.OpenFile(logFile, os.O_CREATE|os.O_APPEND|os.O_RDWR, 0777)
	if fileErr != nil {
		log.Panicf("打开日志文件失败, err :%v", fileErr)
	}

	return log.New(file, "\r\n", log.LstdFlags)
}
